package org.jeecg.common.system.controller;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.ActionEnter;
import org.jeecg.modules.system.entity.SysFile;
import org.jeecg.modules.system.service.ISysFileService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ClassUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Raymee
 * @Email: leohaoo@vip.qq.com
 * @Description:
 * @Date: Created in 13:10 2019/4/21 0021
 */
@Slf4j
@RestController
@RequestMapping("/sys/ueditor")
public class UeditorController {

    @Value(value = "${jeecg.path.upload}")
    private String uploadpath;

    @Value(value = "${jeecg.path.prefix}")
    private String prefixpath;

    @Autowired
    private ISysFileService iSysFileService;

    @RequestMapping(value = "/config")
    public void config(
            HttpServletRequest request,
            HttpServletResponse response,
            @RequestParam(value = "action") String action) {
        PrintWriter out;
        try {
            switch (action) {
                case CommonConstant.SWITCH_CONFIG:
                    log.info("action is config");
                    out = response.getWriter();
                    out.write(new ActionEnter(request, ClassUtils.getDefaultClassLoader().getResource("").getPath()).exec());
                    break;
                case CommonConstant.UPLOAD_IMAGE:
                    log.info("action is uploadimage");
                    SysFile sysFile = this.uploadImage(request, CommonConstant.OTHER_FILE);
                    Map<String, Object> result = new HashMap<>();
                    result.put("state", "SUCCESS");
                    result.put("url", prefixpath + sysFile.getRelativePath());
                    result.put("title", sysFile.getOriginalFileName());
                    result.put("original", sysFile.getOriginalFileName());
                    result.put("type", "jpg");
                    result.put("size", sysFile.getFileSize());
                    out = response.getWriter();
                    out.write(new JSONObject(result).toString());
                    //{"state":"SUCCESS","url":"\/storage\/image\/20190421\/1555835121507355.jpg","title":"1555835121507355.jpg","original":"timg.jpg","type":".jpg","size":211081}
                    //<img src="http://35.201.165.105:8000/storage/image/20190421/1555835121507355.jpg" title="1555835121507355.jpg" alt="timg.jpg"/>
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }

    private SysFile uploadImage(HttpServletRequest request, Integer type) throws IOException {
        String ctxPath = uploadpath;
        String fileName;
        String bizPath = "user";
        String nowday  = new SimpleDateFormat("yyyyMMdd").format(new Date());
        File   file    = new File(ctxPath + File.separator + bizPath + File.separator + nowday);
        if (!file.exists()) {
            file.mkdirs();// 创建文件根目录
        }
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile               mf               = multipartRequest.getFile("file");// 获取上传文件对象
        String                      orgName          = mf.getOriginalFilename();// 获取文件名
        fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
        String savePath = file.getPath() + File.separator + fileName;
        String dbpath   = bizPath + File.separator + nowday + File.separator + fileName;
        if (dbpath.contains("\\")) {
            dbpath = dbpath.replace("\\", "/");
        }
        File savefile = new File(savePath);

        // 新增文件对象
        SysFile sysFile = new SysFile();
        sysFile.setOriginalFileName(orgName);
        sysFile.setType(type);
        sysFile.setRelativePath(dbpath);
        sysFile.setFileSize(mf.getSize());
        sysFile.setCreateTime(new Date());
        iSysFileService.save(sysFile);

        FileCopyUtils.copy(mf.getBytes(), savefile);

        return sysFile;
    }
}
